﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Threading.Tasks;

namespace Common.IO.FileMapping
{
    public enum BuildMapTypes
    {
        StringArray = 1,
        Property = 2
    }

    public static class MapConfig
    {
        private static string ConfigFileName = String.Empty;
        internal static XDocument xdoc = null;

        public static void LoadConfigFile(string FileName)
        {
            if (String.IsNullOrEmpty(FileName)) throw new ArgumentNullException("FileName");
            if (!File.Exists(FileName)) throw new FileNotFoundException(FileName);

            ConfigFileName = FileName;

            xdoc = XDocument.Load(ConfigFileName);

        }

        public static IDictionary<string, string> BuildMap<T>(BuildMapTypes mapType = BuildMapTypes.StringArray)
        {
            if (xdoc.isNull()) throw new Exception("Must load Config file first;");

            Type tType = typeof(T);
            XElement mapName;
            
            switch(mapType)
            {
                case BuildMapTypes.StringArray:
                    mapName = xdoc.XPathSelectElement(String.Format("/FileMapper[@version='1']/Source[@type='StringArray']/Map[@destClass='{0}, {1}']", tType.FullName, tType.Namespace));
                    break;
                case BuildMapTypes.Property:
                    mapName = xdoc.XPathSelectElement(String.Format("/FileMapper[@version='1']/Source[@type='Property']/Map[@destClass='{0}, {1}']", tType.FullName, tType.Namespace));
                    break;
                default:
                    throw new NotImplementedException(mapType.ToString());
            }

            IDictionary<string, string> Mapping = new Dictionary<string, string>();

            mapName.Elements("Property").ForEach(i => Mapping.Add(i.Attribute("src").Value, i.Attribute("dest").Value));

            return Mapping;
        }

    }
}
